import React, { useState, useEffect } from 'react';
import { Input, AutoComplete, Avatar, Typography, Badge, Spin, Empty } from 'antd';
import { SearchOutlined, UserOutlined, ClockCircleOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import api from '../services/api';

const { Text } = Typography;

const StyledItem = styled.div`
  display: flex;
  align-items: center;
  padding: 8px 0;
`;

const ContactInfo = styled.div`
  display: flex;
  flex-direction: column;
  margin-left: 12px;
  overflow: hidden;
  flex: 1;
`;

const StatusBadge = ({ status }) => {
  if (!status) return null;
  
  let color = 'default';
  if (status === 'online') color = 'green';
  else if (status === 'away') color = 'orange';
  
  return <Badge status={color} />;
};

const ContactSearch = () => {
  const [value, setValue] = useState('');
  const [options, setOptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [recentContacts, setRecentContacts] = useState([]);
  const navigate = useNavigate();

  // 获取最近联系人
  useEffect(() => {
    fetchRecentContacts();
  }, []);

  const fetchRecentContacts = async () => {
    try {
      const response = await api.get('/contacts/recent');
      setRecentContacts(response.data.slice(0, 5)); // 只显示前5个
    } catch (error) {
      console.error('获取最近联系人失败:', error);
    }
  };

  // 搜索联系人
  const searchContacts = async (query) => {
    if (!query || query.length < 2) {
      setOptions([]);
      return;
    }

    setLoading(true);
    try {
      const response = await api.get(`/contacts/search?q=${encodeURIComponent(query)}`);
      
      // 转换数据为AutoComplete需要的格式
      const formattedOptions = response.data.map(contact => ({
        value: contact.id.toString(),
        label: (
          <StyledItem>
            <Avatar 
              src={contact.profilePicUrl} 
              icon={<UserOutlined />} 
              size="small"
            />
            <ContactInfo>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <Text strong>{contact.name}</Text>
                <StatusBadge status={contact.status} />
              </div>
              <Text type="secondary" ellipsis style={{ fontSize: '12px' }}>
                {contact.phoneNumber}
              </Text>
            </ContactInfo>
          </StyledItem>
        ),
        contact: contact
      }));
      
      setOptions(formattedOptions);
    } catch (error) {
      console.error('搜索联系人失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (searchText) => {
    setValue(searchText);
    searchContacts(searchText);
  };

  const handleSelect = (contactId) => {
    navigate(`/chat/${contactId}`);
    setValue('');
    setOptions([]);
  };

  // 生成最近联系人选项
  const getRecentContactOptions = () => {
    if (recentContacts.length === 0) {
      return [{ label: <Empty description="无最近联系人" imageStyle={{ height: 40 }} />, disabled: true }];
    }
    
    return recentContacts.map(contact => ({
      value: contact.id.toString(),
      label: (
        <StyledItem>
          <Avatar 
            src={contact.profilePicUrl} 
            icon={<UserOutlined />} 
            size="small"
          />
          <ContactInfo>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Text strong>{contact.name}</Text>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                <ClockCircleOutlined style={{ marginRight: 4 }} />
                {contact.lastMessageTime ? new Date(contact.lastMessageTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}
              </Text>
            </div>
            <Text type="secondary" ellipsis style={{ fontSize: '12px' }}>
              {contact.lastMessage || '开始对话...'}
            </Text>
          </ContactInfo>
        </StyledItem>
      ),
      contact: contact
    }));
  };

  // 当未搜索时，显示最近联系人
  const getCurrentOptions = () => {
    if (value) {
      if (loading) {
        return [{ label: <Spin size="small" />, disabled: true }];
      }
      return options.length > 0 ? options : [{ label: <Empty description="未找到相关联系人" imageStyle={{ height: 40 }} />, disabled: true }];
    }
    return getRecentContactOptions();
  };

  return (
    <AutoComplete
      style={{ width: '100%' }}
      value={value}
      options={getCurrentOptions()}
      onSelect={handleSelect}
      onSearch={handleSearch}
      notFoundContent={null}
      popupMatchSelectWidth={true}
    >
      <Input
        placeholder="搜索联系人..."
        prefix={<SearchOutlined />}
        allowClear
      />
    </AutoComplete>
  );
};

export default ContactSearch; 